"""
配置管理模块 - 负责应用配置的读取、保存和管理
"""

import json
import os
import logging
from typing import Dict, Any, Optional
from datetime import datetime
from .logger import LoggerManager


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_file: str = None, logger_manager: LoggerManager = None, gui_log_callback=None):
        """
        初始化配置管理器
        Args:
            config_file: 配置文件路径，为空则使用默认路径
            logger_manager: 日志管理器实例，为空则创建新的
            gui_log_callback: GUI日志回调函数，格式为 callback(level, message)
        """
        if config_file is None:
            config_dir = os.path.join(os.path.dirname(__file__), '..', 'config')
            os.makedirs(config_dir, exist_ok=True)
            config_file = os.path.join(config_dir, 'settings.json')
        
        self.config_file = config_file
        self.gui_log_callback = gui_log_callback  # 存储GUI日志回调函数
        
        # 使用LoggerManager获取正确配置的logger
        if logger_manager is None:
            logger_manager = LoggerManager()
        self.logger = logger_manager.get_logger(__name__)
        
        self.config = self.load_config()
    
    def get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            "app": {
                "name": "富途牛牛监控",
                "version": "1.0.0",
                "window_width": 1200,
                "window_height": 600,
                "left_panel_ratio": 0.7,  # 左侧面板比例
                "right_panel_ratio": 0.3  # 右侧面板比例
            },
            "ocr": {
                "api_url": "http://127.0.0.1:9003/ocr",
                "timeout": 30,
                "auto_start_service": True
            },
            "area": {
                "recognition_areas": [],  # 识别区域配置列表
                "current_area": None     # 当前选择的区域
            },
            "trading": {
                "password": "",          # 交易密码（加密存储）
                "auto_trade": False,     # 自动交易开关
                "trade_interval": 5      # 交易间隔（秒）
            },
            "monitor": {
                "running": False,        # 监控运行状态
                "start_time": None,      # 开始时间
                "end_time": None,        # 结束时间
                "monitor_interval": 3    # 监控间隔（秒）
            },
            "history": {
                "max_records": 50,       # 最大记录数
                "records": []            # 操作历史记录
            },
            "log": {
                "level": "INFO",
                "save_to_file": True,
                "max_file_size": "10MB"
            },
            "created_time": datetime.now().isoformat(),
            "last_updated": datetime.now().isoformat()
        }
    
    def load_config(self) -> Dict[str, Any]:
        """
        加载配置文件
        Returns:
            配置字典
        """
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.logger.info(f"配置文件加载成功: {self.config_file}")
                    
                    # 合并默认配置（确保新增的配置项存在）
                    default_config = self.get_default_config()
                    merged_config = self.merge_config(default_config, config)
                    
                    return merged_config
            else:
                self.logger.info("配置文件不存在，使用默认配置")
                return self.get_default_config()
                
        except Exception as e:
            self.logger.error(f"加载配置文件失败: {e}")
            self.logger.info("使用默认配置")
            return self.get_default_config()
    
    def merge_config(self, default: Dict, user: Dict) -> Dict:
        """递归合并配置，保留用户配置，补充默认配置"""
        result = default.copy()
        
        for key, value in user.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = self.merge_config(result[key], value)
            else:
                result[key] = value
        
        return result
    
    def save_config(self) -> bool:
        """
        保存配置到文件
        Returns:
            是否保存成功
        """
        try:
            # 更新最后修改时间
            self.config['last_updated'] = datetime.now().isoformat()
            
            # 创建配置目录
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
            
            # 保存配置文件
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=2, ensure_ascii=False)
            
            self.logger.info(f"配置文件保存成功: {self.config_file}")
            return True
            
        except Exception as e:
            self.logger.error(f"保存配置文件失败: {e}")
            return False
    
    def get(self, key_path: str, default=None):
        """
        获取配置值
        Args:
            key_path: 配置路径，如 'app.window_width'
            default: 默认值
        Returns:
            配置值
        """
        try:
            keys = key_path.split('.')
            value = self.config
            
            for key in keys:
                if isinstance(value, dict) and key in value:
                    value = value[key]
                else:
                    return default
            
            return value
            
        except Exception as e:
            self.logger.error(f"获取配置失败: {key_path}, {e}")
            return default
    
    def set(self, key_path: str, value: Any) -> bool:
        """
        设置配置值
        Args:
            key_path: 配置路径，如 'app.window_width'
            value: 配置值
        Returns:
            是否设置成功
        """
        try:
            keys = key_path.split('.')
            config_ref = self.config
            
            # 导航到父级配置项
            for key in keys[:-1]:
                if key not in config_ref:
                    config_ref[key] = {}
                config_ref = config_ref[key]
            
            # 设置值
            config_ref[keys[-1]] = value
            
            
            return True
            
        except Exception as e:
            self.logger.error(f"设置配置失败: {key_path} = {value}, {e}")
            return False
    
    def add_recognition_area(self, name: str, bbox: tuple, description: str = "") -> bool:
        """
        添加识别区域
        Args:
            name: 区域名称
            bbox: 区域坐标 (left, top, right, bottom)
            description: 区域描述
        Returns:
            是否添加成功
        """
        try:
            area_config = {
                "name": name,
                "bbox": bbox,
                "description": description,
                "created_time": datetime.now().isoformat(),
                "enabled": True
            }
            
            areas = self.get('area.recognition_areas', [])
            
            # 检查是否已存在同名区域
            for area in areas:
                if area['name'] == name:
                    self.logger.warning(f"区域名称已存在: {name}")
                    return False
            
            areas.append(area_config)
            self.set('area.recognition_areas', areas)
            
            self.logger.info(f"识别区域添加成功: {name}")
            return True
            
        except Exception as e:
            self.logger.error(f"添加识别区域失败: {e}")
            return False
    
    def remove_recognition_area(self, name: str) -> bool:
        """删除识别区域"""
        try:
            areas = self.get('area.recognition_areas', [])
            areas = [area for area in areas if area['name'] != name]
            self.set('area.recognition_areas', areas)
            
            # 如果删除的是当前区域，清空当前区域
            if self.get('area.current_area') == name:
                self.set('area.current_area', None)
            
            self.logger.info(f"识别区域删除成功: {name}")
            return True
            
        except Exception as e:
            self.logger.error(f"删除识别区域失败: {e}")
            return False
    
    def get_recognition_areas(self) -> list:
        """获取所有识别区域"""
        return self.get('area.recognition_areas', [])
    
    def add_history_record(self, action: str, details: str, status: str = "success") -> bool:
        """
        添加操作历史记录（简单版本，兼容旧代码）
        Args:
            action: 操作类型
            details: 操作详情
            status: 操作状态
        Returns:
            是否添加成功
        """
        try:
            record = {
                "timestamp": datetime.now().isoformat(),
                "action": action,
                "details": details,
                "status": status
            }
            
            records = self.get('history.records', [])
            records.append(record)
            
            # 限制记录数量
            max_records = self.get('history.max_records', 50)
            if len(records) > max_records:
                records = records[-max_records:]  # 保留最新的记录
            
            self.set('history.records', records)
            self.logger.info(f"操作记录添加: {action}")
            
            return True
            
        except Exception as e:
            self.logger.error(f"添加操作记录失败: {e}")
            return False
    
    def add_trading_record(self, stock_code: str, direction: str, quantity: int, amount: float, 
                          prev_position: float, current_position: float, position_diff: float,
                          account_funds: float, ocr_status: str, record_id: str = None) -> str:
        """
        添加详细的交易记录
        Args:
            stock_code: 股票代码
            direction: 交易方向 (买入/卖出)
            quantity: 数量
            amount: 金额
            prev_position: 变化前仓位
            current_position: 当前仓位
            position_diff: 仓位差距
            account_funds: 当前账户资金
            ocr_status: OCR识别的状态字段
            record_id: 记录ID，用于更新现有记录
        Returns:
            记录ID
        """
        try:
            current_time = datetime.now().isoformat()
            
            # 处理状态显示：将"部成交"转换为"全部成交"
            display_status = ocr_status
            if "部成交" in ocr_status:
                display_status = "全部成交"  # 直接替换为"全部成交"，避免重复
            
            # 判断是否为成交状态（精确匹配，避免"未成交"和"待成交"被误判）
            is_executed = (("部成交" in ocr_status or "全部成交" in ocr_status) and 
                          "未成交" not in ocr_status and "待成交" not in ocr_status)
            
            if record_id:
                # 更新现有记录
                trading_records = self.get('trading.records', [])
                for record in trading_records:
                    if record.get('record_id') == record_id:
                        # 检查是否状态发生变化（在更新前获取旧状态）
                        old_operation_time = record.get('operation_time')
                        position_info = f"{prev_position:.1f}% → {current_position:.1f}%"
                        amount_info = f"${amount:,.2f}"
                        
                        # 更新记录，但保持原始记录时间
                        record.update({
                            'direction': direction,
                            'quantity': quantity,
                            'amount': amount,
                            'prev_position': prev_position,
                            'current_position': current_position,
                            'position_diff': position_diff,
                            'account_funds': account_funds,
                            'ocr_status': display_status,
                            'operation_time': current_time if is_executed else record.get('operation_time')
                        })
                        self.set('trading.records', trading_records)
                        
                        # 输出状态变化日志
                        if old_operation_time is None and is_executed:
                            # 从待成交变为已执行
                            log_message = f"🟡 状态变更: {stock_code} {direction} | 从待执行变为已执行 | 仓位: {position_info} | 数量: {quantity} | 金额: {amount_info}"
                            self.logger.info(log_message)
                            # 发送到GUI界面
                            if self.gui_log_callback:
                                self.gui_log_callback("TRADE_UPDATED", log_message)
                        elif is_executed:
                            # 已执行状态的更新
                            log_message = f"🟢 交易更新: {stock_code} {direction} | 仓位: {position_info} | 数量: {quantity} | 金额: {amount_info} | 状态: {display_status}"
                            self.logger.info(log_message)
                            # 发送到GUI界面
                            if self.gui_log_callback:
                                self.gui_log_callback("TRADE_EXECUTED", log_message)
                        else:
                            # 待成交状态的更新
                            self.logger.info(f"🔴 记录更新: {stock_code} {direction} | 仓位: {position_info} | 数量: {quantity} | 金额: {amount_info} | 状态: {display_status} (待执行)")
                        
                        return record_id
                
            # 创建新记录
            new_record_id = f"{stock_code}_{current_time}_{direction}"
            record = {
                'record_id': new_record_id,
                'stock_code': stock_code,
                'direction': direction,
                'quantity': quantity,
                'amount': amount,
                'prev_position': prev_position,
                'current_position': current_position,
                'position_diff': position_diff,
                'account_funds': account_funds,
                'ocr_status': display_status,
                'record_time': current_time,
                'operation_time': current_time if is_executed else None
            }
            
            trading_records = self.get('trading.records', [])
            trading_records.append(record)
            
            # 限制记录数量
            max_records = self.get('trading.max_records', 100)
            if len(trading_records) > max_records:
                trading_records = trading_records[-max_records:]
            
            self.set('trading.records', trading_records)
            
            # 根据交易状态输出不同的日志信息
            position_info = f"{prev_position:.1f}% → {current_position:.1f}%"
            amount_info = f"${amount:,.2f}"
            
            if is_executed:
                # 已执行交易 - 绿色标记
                log_message = f"🟢 交易执行: {stock_code} {direction} | 仓位: {position_info} | 数量: {quantity} | 金额: {amount_info} | 状态: {display_status}"
                self.logger.info(log_message)
                # 发送到GUI界面
                if self.gui_log_callback:
                    self.gui_log_callback("TRADE_EXECUTED", log_message)
            else:
                # 待成交交易 - 红色标记  
                log_message = f"🔴 交易记录: {stock_code} {direction} | 仓位: {position_info} | 数量: {quantity} | 金额: {amount_info} | 状态: {display_status} (待执行)"
                self.logger.info(log_message)
                # 发送到GUI界面
                if self.gui_log_callback:
                    self.gui_log_callback("TRADE_PENDING", log_message)
            
            return new_record_id
            
        except Exception as e:
            self.logger.error(f"添加交易记录失败: {e}")
            return None
    
    def update_pending_trading_records(self, stock_code: str, new_ocr_status: str):
        """
        更新指定股票的待成交记录
        Args:
            stock_code: 股票代码
            new_ocr_status: 新的OCR状态
        """
        try:
            trading_records = self.get('trading.records', [])
            current_time = datetime.now().isoformat()
            
            # 处理状态显示
            display_status = new_ocr_status
            if "部成交" in new_ocr_status:
                display_status = new_ocr_status.replace("部成交", "全部成交")
            
            is_executed = (("部成交" in new_ocr_status or "全部成交" in new_ocr_status) and 
                          "未成交" not in new_ocr_status and "待成交" not in new_ocr_status)
            
            updated_count = 0
            executed_count = 0
            for record in trading_records:
                # 查找该股票的待成交记录（operation_time为None的记录，表示尚未实际执行交易）
                if (record.get('stock_code') == stock_code and 
                    record.get('operation_time') is None):
                    
                    direction = record.get('direction', '未知')
                    prev_pos = record.get('prev_position', 0)
                    curr_pos = record.get('current_position', 0)
                    amount = record.get('amount', 0)
                    
                    # 更新为成交状态
                    record['ocr_status'] = display_status
                    if is_executed:
                        record['operation_time'] = current_time
                        executed_count += 1
                        # 从待成交变为已执行的日志
                        self.logger.info(f"🟡 批量状态变更: {stock_code} {direction} | 从待执行变为已执行 | 仓位: {prev_pos:.1f}% → {curr_pos:.1f}% | 金额: ${amount:,.2f}")
                    
                    updated_count += 1
            
            if updated_count > 0:
                self.set('trading.records', trading_records)
                if executed_count > 0:
                    self.logger.info(f"📊 批量更新完成: {stock_code} 共更新 {updated_count} 条记录，其中 {executed_count} 条变为已执行")
                else:
                    self.logger.info(f"📊 批量更新完成: {stock_code} 共更新 {updated_count} 条记录状态")
                
        except Exception as e:
            self.logger.error(f"更新待成交记录失败: {e}")
    
    def get_trading_records(self) -> list:
        """获取交易记录"""
        return self.get('trading.records', [])
    
    def get_history_records(self) -> list:
        """获取操作历史记录"""
        return self.get('history.records', [])
    
    def clear_history(self) -> bool:
        """清空操作历史"""
        try:
            self.set('history.records', [])
            self.logger.info("操作历史已清空")
            return True
        except Exception as e:
            self.logger.error(f"清空操作历史失败: {e}")
            return False
    
    def auto_save(self):
        """自动保存配置"""
        self.save_config()
